using System;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace MLTimeline.Editor
{
    public class TimelineView : VisualElement
    {
        private VisualElement _leftPanel;
        private ToolbarButton _addTrackButton;
        private ScrollView _trackPanel;
        private VisualElement _rulerPanel;
        private VisualElement _dragLine;
        private RulerView _rulerView;

        // 用于存储拖拽开始时的状态
        private Vector2 _startMousePosition;
        private float _startLeftPanelWidth;

        public TimelineView()
        {
            CreateGUI();
            schedule.Execute(Initialize);
        }

        private void CreateGUI()
        {
            var loader = TimelineEditorLoader.Instance;
            if (loader == null)
            {
                Debug.LogWarning("当前加载器不存在。");
                return;
            }
            if (loader.timelineView == null)
            {
                Debug.LogWarning("timeline-view.uxml文件不存在，请检查下，是否将uxml文件拖入TimelineEditorLoader.cs文件的Inspector面板内。");
                return;
            }
            loader.timelineView.CloneTree(this);
            _leftPanel = this.Q("left-panel");
            _addTrackButton = _leftPanel.Q<ToolbarButton>("add-track-button");
            _trackPanel = _leftPanel.Q<ScrollView>("track-panel");
            _rulerPanel = this.Q("ruler-view-panel");
            _dragLine = this.Q("drag-line");
            _dragLine.AddToClassList("cursorResizeHorizontal");
            _leftPanel.style.width = _leftPanel.resolvedStyle.minWidth.value > 0 ? _leftPanel.resolvedStyle.minWidth.value : 200;
            _rulerView = new RulerView();
            _rulerPanel.Add(_rulerView);

            _addTrackButton.clicked += () =>
            {
                _trackPanel.Add(new TrackView());
                _rulerView.AddTrackPlate();
            };
            _dragLine.RegisterCallback<MouseDownEvent>(OnMouseDown);
            _trackPanel.verticalScroller.slider.RegisterValueChangedCallback(OnTrackScrollChanged);

            _trackPanel.Add(new TrackView());
            _rulerView.AddTrackPlate();
            _trackPanel.Add(new TrackView());
            _rulerView.AddTrackPlate();
        }

        private void Initialize()
        {
            this.StretchToParentSize();
        }

        private void OnMouseDown(MouseDownEvent evt)
        {
            // 记录拖拽起始状态
            _startMousePosition = evt.mousePosition;
            _startLeftPanelWidth = _leftPanel.resolvedStyle.width;

            // 在父容器上注册移动和松开事件，以便在整个视图内拖拽
            RegisterCallback<MouseMoveEvent>(OnMouseMove);
            RegisterCallback<MouseUpEvent>(OnMouseUp);

            // 捕获鼠标，确保事件不会丢失
            this.CaptureMouse();
            evt.StopPropagation();
        }

        private void OnMouseMove(MouseMoveEvent evt)
        {
            float deltaX = evt.mousePosition.x - _startMousePosition.x;

            float newWidth = _startLeftPanelWidth + deltaX;

            float minWidth = _leftPanel.resolvedStyle.minWidth.value;
            float maxWidth = _leftPanel.resolvedStyle.maxWidth.value;

            // 将新宽度限制在最小和最大值之间
            newWidth = Mathf.Clamp(newWidth, minWidth, maxWidth);

            _leftPanel.style.width = newWidth;

            evt.StopPropagation();
        }

        private void OnMouseUp(MouseUpEvent evt)
        {
            this.ReleaseMouse();
            // 从父容器上注销事件，因为拖拽已结束
            UnregisterCallback<MouseMoveEvent>(OnMouseMove);
            UnregisterCallback<MouseUpEvent>(OnMouseUp);
            evt.StopPropagation();
        }

        // 当左侧轨道列表滚动时调用
        private void OnTrackScrollChanged(ChangeEvent<float> evt)
        {
            if (_rulerView == null) return;
            _rulerView.TrackPlatePanel.verticalScroller.slider.value = evt.newValue;
        }
    }
}